package com.cqs.leetcode.array;

import com.cqs.leetcode.ds.ArraysUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * lixw
 * 2021/11/4
 **/
public class FindNumbersDisappearedArray {

    public List<Integer> findDisappearedNumbers2(int[] nums) {
        List<Integer> list = new ArrayList<>();

        // [1,2,3,3,4,4,7,8]
        // [1,2,3,3,4,7,8,8,10]
        Arrays.sort(nums);
        //[1,2,3,4,7,8]
        int left = 0, cnt = 0;
        for (int i = 0; i < nums.length; i++) {
            //找到最后一个和num[i]相等的元素
            while (i + 1 < nums.length && nums[i] == nums[i + 1]) {
                i++;
                ++cnt;
            }
            nums[left++] = nums[i];
        }
        //handler first number
        int expect = 1;
        while (expect < nums[0]) {
            list.add(expect++);
        }

        //[2,2,3,3,5] --> [2,3,5]
        //find disappear number
        for (int i = 1; i < nums.length - cnt; i++) {
            for (int j = nums[i - 1] + 1; j < nums[i]; j++) {
                list.add(j);
            }
        }
        //[1,2] 缺少3和4
        for (int i = nums[nums.length - 1 - cnt]; i < nums.length; i++) {
            list.add(i + 1);
        }
        return list;
    }

    public List<Integer> findDisappearedNumbers(int[] nums) {
        int[] bucket = new int[nums.length];
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            bucket[nums[i] - 1] = nums[i];
        }
        for (int i = 0; i < bucket.length; i++) {
            if (bucket[i] == 0) {
                list.add(i + 1);
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<int[]> cases = new ArrayList<>();
        cases.add(new int[]{1,2,3,3,4,7,8,8,8,10});
        cases.add(new int[]{2,2,3,3,4,7,8,8,8,9});
        cases.add(new int[]{4, 3, 2, 7, 8, 2, 3, 1});
        cases.add(new int[]{1, 2, 3, 4, 5, 5});
        cases.add(new int[]{1, 1});
        cases.add(new int[]{2, 2, 2});
        FindNumbersDisappearedArray a = new FindNumbersDisappearedArray();
        for (int[] c : cases) {
            System.out.println(ArraysUtils.formatInts(c) + " ---- " + a.findDisappearedNumbers(c));
            System.out.println(ArraysUtils.formatInts(c) + " ---- " + a.findDisappearedNumbers2(c));
        }

    }


}
